﻿using GarminConnect;
using System.IO.Compression;

namespace GarminUtils
{
    /// <summary>
    /// 佳明国区
    /// </summary>
    public class GarminCN
    {
        // 环境变量读取，带默认值
        private static readonly string GARMIN_USERNAME = Environment.GetEnvironmentVariable("GARMIN_USERNAME") ?? Constant.GarminUsernameDefault;
        private static readonly string GARMIN_PASSWORD = Environment.GetEnvironmentVariable("GARMIN_PASSWORD") ?? Constant.GarminPasswordDefault;
        private static readonly string GARMIN_MIGRATE_NUM = Environment.GetEnvironmentVariable("GARMIN_MIGRATE_NUM") ?? Constant.GarminMigrateNumDefault.ToString();
        private static readonly string GARMIN_MIGRATE_START = Environment.GetEnvironmentVariable("GARMIN_MIGRATE_START") ?? Constant.GarminMigrateStartDefault.ToString();
        private static readonly int GARMIN_SYNC_NUM = int.TryParse(Environment.GetEnvironmentVariable("GARMIN_SYNC_NUM"), out var syncNum) ? syncNum : Constant.GarminSyncNumDefault;

        public static async Task<GarminConnectClient> GetGaminCNClientAsync()
        {
            if (string.IsNullOrWhiteSpace(GARMIN_USERNAME) || string.IsNullOrWhiteSpace(GARMIN_PASSWORD))
            {
                var errMsg = "请填写中国区用户名及密码：GARMIN_USERNAME,GARMIN_PASSWORD";
                Console.Error.WriteLine(errMsg);
                // 这里可以抛异常或者返回null，根据需求调整
                throw new ArgumentException(errMsg);
            }

            var GCClient = new GarminConnectClient(new GCCredentials
            {
                Username = GARMIN_USERNAME,
                Password = GARMIN_PASSWORD
            },GarminDomain.GarminCN);

            try
            {
                //await SqliteHelper.InitDBAsync();

                //var currentSession = await SqliteHelper.GetSessionFromDBAsync("CN");
                //if (currentSession == null)
                //{
                //    await GCClient.LoginAsync();
                //    await SqliteHelper.SaveSessionToDBAsync("CN", GCClient.ExportToken());
                //}
                //else
                //{
                //    try
                //    {
                //        Console.WriteLine("GarminCN: login by saved session");
                //        await GCClient.LoadTokenAsync(currentSession.OAuth1, currentSession.OAuth2);
                //    }
                //    catch (Exception)
                //    {
                //        Console.WriteLine("Warn: renew GarminCN Session..");
                //        await GCClient.LoginAsync(GARMIN_USERNAME, GARMIN_PASSWORD);
                //        await SqliteHelper.UpdateSessionToDBAsync("CN", GCClient.SessionJson);
                //    }
                //}

                await GCClient.LoginAsync();

                var userInfo = await GCClient.GetUserProfileAsync();
                var fullName = userInfo.FullName;
                var emailAddress = userInfo.UserName;
                var location = userInfo.Location;

                if (string.IsNullOrEmpty(fullName))
                {
                    throw new Exception("佳明中国区登录失败");
                }

                Console.WriteLine($"Garmin userInfo CN: fullName={fullName}, emailAddress={emailAddress}, location={location}");

                return GCClient;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                // 这里可以根据需要抛异常或者返回null
                throw;
            }
        }

        public static async Task MigrateGarminCN2GarminGlobalAsync(int count = 200)
        {
            int actIndex = int.TryParse(GARMIN_MIGRATE_START, out var start) ? start : 0;
            int totalAct = int.TryParse(GARMIN_MIGRATE_NUM, out var migrateNum) ? migrateNum : count;

            var clientCN = await GetGaminCNClientAsync();
            var clientGlobal = await GarminGlobal.GetGarminGlobalClientAsync();

            var actSlices = await clientCN.GetActivitiesAsync(actIndex, totalAct);

            // 这里注释掉了筛选running的逻辑，保持和原代码一致
            var runningActs = actSlices;

            string downloadDir = "";

            for (int j = 0; j < runningActs.Count; j++)
            {
                var act = runningActs[j];
                // 下载佳明原始数据
                await clientCN.DownloadOriginalActivityDataAsync(act.ActivityId, Path.Combine(downloadDir, $"{act.ActivityId}.zip"));

                //解压数据
                var fitFilePath = await UnZipGarminActivityAsync(downloadDir, act.ActivityId);

                Console.WriteLine($"本次开始向国际区上传第 {NumberTricks.Number2Capital(j + 1)} 条数据，相对总数上传到 {NumberTricks.Number2Capital(j + 1 + actIndex)} 条，  【 {act.ActivityName} 】，开始于 【 {act.StartTimeLocal} 】，活动ID: 【 {act.ActivityId} 】");

                await clientGlobal.UploadActivityAsync(fitFilePath);

                // 如果需要延时，可以用下面代码
                // await Task.Delay(2000);
            }
        }

        /// <summary>
        /// 解压佳明活动数据
        /// </summary>
        /// <param name="downloadDir"></param>
        /// <param name="activityId"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private static async Task<string> UnZipGarminActivityAsync(string downloadDir,int activityId) 
        {
            if (!Directory.Exists(downloadDir))
            {
                Directory.CreateDirectory(downloadDir);
            }

            string originZipFile = Path.Combine(downloadDir, $"{activityId}.zip");

            // 解压目录，这里用同一个目录
            string extractDir = downloadDir;

            // 解压 zip 文件
            ZipFile.ExtractToDirectory(originZipFile, extractDir, overwriteFiles: true);

            // 获取解压后的第一个文件路径
            string[] extractedFiles = Directory.GetFiles(extractDir);

            if (extractedFiles.Length == 0)
            {
                throw new Exception("解压后没有找到文件");
            }

            string unzippedFilePath = extractedFiles[0];

            Console.WriteLine("DownloadGarminActivity - path: " + unzippedFilePath);

            return unzippedFilePath;
        }

        //public static async Task SyncGarminCN2GarminGlobalAsync()
        //{
        //    var clientCN = await GetGaminCNClientAsync();
        //    var clientGlobal = await GarminGlobalService.GetGaminGlobalClientAsync();

        //    var cnActs = await clientCN.GetActivitiesAsync(0, GARMIN_SYNC_NUM);
        //    var globalActs = await clientGlobal.GetActivitiesAsync(0, 1);

        //    var latestGlobalActStartTime = globalActs.FirstOrDefault()?.StartTimeLocal ?? "0";
        //    var latestCnActStartTime = cnActs.FirstOrDefault()?.StartTimeLocal ?? "0";

        //    if (latestCnActStartTime == latestGlobalActStartTime)
        //    {
        //        Console.WriteLine($"没有要同步的活动内容, 最近的活动:  【 {cnActs[0].ActivityName} 】, 开始于: 【 {latestCnActStartTime} 】");
        //    }
        //    else
        //    {
        //        cnActs.Reverse(); // 反转列表，等同于lodash的_.reverse

        //        int actualNewActivityCount = 1;
        //        foreach (var cnAct in cnActs)
        //        {
        //            if (string.Compare(cnAct.StartTimeLocal, latestGlobalActStartTime) > 0)
        //            {
        //                var filePath = await GarminCommon.DownloadGarminActivityAsync(cnAct.ActivityId, clientCN);

        //                Console.WriteLine($"本次开始向国际区上传第 {NumberTricks.Number2Capital(actualNewActivityCount)} 条数据，【 {cnAct.ActivityName} 】，开始于 【 {cnAct.StartTimeLocal} 】，活动ID: 【 {cnAct.ActivityId} 】");

        //                await GarminCommon.UploadGarminActivityAsync(filePath, clientGlobal);

        //                await Task.Delay(1000);

        //                actualNewActivityCount++;
        //            }
        //        }
        //    }
        //}
    }
}
